package com.franklin.ideaplugin.api.utils.psi;

import com.google.common.collect.Maps;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypes;
import com.intellij.psi.search.GlobalSearchScope;

import java.util.Map;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2024/3/21
 */
public class PsiTypeUtils {

    private final static Map<String,PsiType> simplePsiTypes = Maps.newHashMap();

    static {
        simplePsiTypes.put(int.class.getName(),PsiTypes.booleanType());
        simplePsiTypes.put(Boolean.class.getName(),PsiTypes.booleanType());
        simplePsiTypes.put(byte.class.getName(),PsiTypes.byteType());
        simplePsiTypes.put(Byte.class.getName(),PsiTypes.byteType());
        simplePsiTypes.put(short.class.getName(),PsiTypes.shortType());
        simplePsiTypes.put(Short.class.getName(),PsiTypes.shortType());
        simplePsiTypes.put(int.class.getName(),PsiTypes.intType());
        simplePsiTypes.put(Integer.class.getName(),PsiTypes.intType());
        simplePsiTypes.put(long.class.getName(),PsiTypes.longType());
        simplePsiTypes.put(Long.class.getName(),PsiTypes.longType());
        simplePsiTypes.put(float.class.getName(),PsiTypes.floatType());
        simplePsiTypes.put(Float.class.getName(),PsiTypes.floatType());
        simplePsiTypes.put(double.class.getName(),PsiTypes.doubleType());
        simplePsiTypes.put(Double.class.getName(),PsiTypes.doubleType());
    }

    /**
     * 获取psiType
     * @param classQualifiedName
     * @param project
     * @return
     */
    public static PsiType getPsiType(String classQualifiedName, Project project){
        PsiType psiType = simplePsiTypes.get(classQualifiedName);
        if (Objects.nonNull(psiType)){
            return psiType;
        }
        return PsiType.getTypeByName(classQualifiedName,project, GlobalSearchScope.allScope(project));
    }

    /**
     * 是否是java map类型
     * @param psiType
     * @return
     */
    public static boolean isJavaMapType(PsiType psiType){
        if (!PsiClassType.class.isInstance(psiType)){
            return false;
        }
        PsiClassType psiClassType = (PsiClassType) psiType;
        PsiClass psiClass = psiClassType.resolve();
        return PsiClassUtils.isJavaMapClass(psiClass);
    }
}
